package com.xinzhi.log.service.impl;

import com.xinzhi.log.service.IncomeAndExpensesLog;
import com.xinzhi.mapper.IncomeAndExpensesMapper;
import com.xinzhi.pojo.Bankaccount;
import com.xinzhi.pojo.Incomeandexpenditurerecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

@Service
public class IncomeAndExpensesLogService implements IncomeAndExpensesLog {
    @Autowired
    private IncomeAndExpensesMapper incomeAndExpensesMapper;
    @Override
    @Async("taskExecutor")
    public void addIncomeAndExpenses(Bankaccount from, Bankaccount to, Double money) {
        Incomeandexpenditurerecord incomeandexpenditurerecord = new Incomeandexpenditurerecord();

        //自己
        incomeandexpenditurerecord.setUserId(from.getId());
        incomeandexpenditurerecord.setTransactionCard(from.getCardNumber());
        incomeandexpenditurerecord.setTransactionAccount(from.getUsername());
        incomeandexpenditurerecord.setTransactionType("网转");
        incomeandexpenditurerecord.setTradingFloor("手机银行");
        //对方
        incomeandexpenditurerecord.setReciprocalCard(to.getCardNumber());
        incomeandexpenditurerecord.setReciprocalName(to.getUsername());
        incomeandexpenditurerecord.setReciprocalOpeningBank(to.getOpeningBank());

        incomeandexpenditurerecord.setBalance(to.getMoney() + money);
        incomeandexpenditurerecord.setAmount(money);
        incomeandexpenditurerecord.setAccountAmount(money);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss", Locale.CHINA);
        LocalDateTime now = LocalDateTime.now();
        incomeandexpenditurerecord.setTradingHour(now.format(formatter));

        if (incomeandexpenditurerecord.getUserId() == null) {
            throw new RuntimeException("账户id不能为空");
        }
        //检查交易类型是否合法
        if (incomeandexpenditurerecord.getTransactionType() == null) {
            throw new RuntimeException("交易类型不能为空");
        }
        //检查交易金额是否合法
        if (incomeandexpenditurerecord.getAmount() == null) {
            throw new RuntimeException("交易金额不能为空");
        }
        incomeAndExpensesMapper.addIncomeAndExpenses(incomeandexpenditurerecord);
    }
}
